package com.ship.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.banboocloud.Codec.Sm3Signature;
import com.banboocloud.Codec.Sm4Cipher;
import com.ship.auth.entity.vo.RegisterVo;
import com.ship.auth.service.UserCreateService;
import com.ship.auth.uitl.BamboocloudUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;

import java.util.*;

//import static com.ship.auth.uitl.BamboocloudUtils.verify;
@RestController
@RequestMapping("/idp/oauth2")
@CrossOrigin
public class SyncController {

    @Autowired
    private UserCreateService userCreateService;

    @Value("${authentication.secret.key}")
    private String key;

    @PostMapping("/SchemaService")
    public String SchemaService(@RequestBody String ciphertext){
        System.out.println("进入SchemaService接口");
        System.out.println(ciphertext);

//        String key = "X2!k4@L7#q9M6p8R";//测试环境
        String key = "F9#q7A@3r5G6p2WR";//生产环境
        Map<String, Object> result = new HashMap<>();
//        JSONObject jsonObject = JSON.parseObject(ciphertext);
//        String text = jsonObject.getString("ciphertext");
        System.out.println("预备创建Sm4Cipher");
        Sm4Cipher sm4Cipher = new Sm4Cipher();
        System.out.println("创建成功");
        try {
            System.out.println("进入try");
            Map<String,Object> reqmap = ((Map<String,Object>) JSON.parse(sm4Cipher.decrypt(ciphertext, key)));
            String bimRequestId = (String) reqmap.get("bimRequestId");
            result.put("bimRequestId", bimRequestId);

            List<Object> accountAttributes = new ArrayList<>();
//            accountAttributes.add(createAccountAttribute("id", "int", true, false));
//            accountAttributes.add(createAccountAttribute("password", "String", false, false));
            accountAttributes.add(createAccountAttribute("username", "String", false, false));
//            accountAttributes.add(createAccountAttribute("avatar", "String", false, false));
//            accountAttributes.add(createAccountAttribute("is_disabled", "int", false, false));
//            accountAttributes.add(createAccountAttribute("create_date", "String", false, false));
//            accountAttributes.add(createAccountAttribute("create_by", "String", false, false));
//            accountAttributes.add(createAccountAttribute("bim_remote_user", "String", false, false));
//            accountAttributes.add(createAccountAttribute("bim_remote_pwd", "String", false, false));
//            accountAttributes.add(createAccountAttribute("uid", "String", false, false));

            result.put("account", accountAttributes);
            String target2 = sm4Cipher.encrypt(JSON.toJSONString(result), key);
            System.out.println(sm4Cipher.decrypt(target2,key));
            return target2;
        }catch (Exception ignored){
            System.out.println(ignored.getMessage());
            result.put("error",ignored.getMessage());
        }
        String target2 = sm4Cipher.encrypt(JSON.toJSONString(result), key);
        return target2;
    }

    @PostMapping("/UserCreateService")
    public String UserCreateService(@RequestBody String ciphertext){
        System.out.println("进入UserCreateService接口");
        System.out.println(ciphertext);
        Map<String, Object> result = new HashMap<>();
//        JSONObject jsonObject = JSON.parseObject(ciphertext);
//        String text = jsonObject.getString("ciphertext");
//        System.out.println("密文:--"+text);
//        String key = "X2!k4@L7#q9M6p8R";//测试环境
        String key = "F9#q7A@3r5G6p2WR";//生产环境
        Sm4Cipher sm4Cipher = new Sm4Cipher();

        if (ciphertext.isEmpty()){
            result.put("bimRequestId","");
            result.put("resultCode", 500);
            result.put("message", "账号创建失败,请联系管理员");
            String target2 = sm4Cipher.encrypt(JSON.toJSONString(result), key);
            return target2;
        }

        Map<String,Object> reqmap = ((Map<String,Object>) JSON.parse(sm4Cipher.decrypt(ciphertext, key)));

        String bimRequestId = (String) reqmap.get("bimRequestId");
        String bimRemoteUser = (String) reqmap.get("bimRemoteUser");
//        String bimRemotePwd = (String) reqmap.get("bimRemotePwd");
        String username = (String) reqmap.get("username");
//        String password = (String) reqmap.get("password");

        //判断用户名
        System.out.println("bimRemoteUser:"+bimRemoteUser);
//        System.out.println("bimRemotePwd:"+bimRemotePwd);

        if (BamboocloudUtils.verify(reqmap,"SM3").booleanValue()) {
            System.out.println("验签成功");
            RegisterVo registerVo = new RegisterVo();
            registerVo.setUserName(username);
//            registerVo.setPassword(password);
//            registerVo.setBimRemotePwd(bimRemotePwd);
            registerVo.setBimRemoteUser(bimRemoteUser);

            String uid = userCreateService.addUser(registerVo);
    //        System.out.println("Request: " + request.toString());
    //        System.out.println("Response: " + response.toString());
    //        System.out.println("Handler: " + handler.toString());
    //        System.out.println("RegisterVo: " + registerVo.toString());

    //            result.put("bimRequestId", registerVo.getBimRequestId());
    //        result.put("bimRemotePwd", registerVo.getBimRemotePwd());

            if (Objects.equals(uid, "")){
                result.put("bimRequestId", bimRequestId);
                result.put("resultCode", 500);
                result.put("message", "账号已存在");

                String target2 = sm4Cipher.encrypt(JSON.toJSONString(result), key);
                return target2;
            }
            else{
                result.put("bimRequestId", bimRequestId);
                result.put("uid", uid);
                result.put("resultCode", "0");
                result.put("message", "success");
                String target2 = sm4Cipher.encrypt(JSON.toJSONString(result), key);
                return target2;
            }
        }
        result.put("bimRequestId", bimRequestId);
        result.put("resultCode", 500);
        result.put("message", "验签失败");
        String target2 = sm4Cipher.encrypt(JSON.toJSONString(result), key);
        return target2;
    }

    @PostMapping("/UserUpdateService")
//    public String UserUpdateService(@RequestBody RegisterVo registerVo){
    public String UserUpdateService(@RequestBody String ciphertext){
//    public Map<String, Object> UserUpdateService(@RequestBody String ciphertext){
        System.out.println("进入UserUpdateService接口");
        System.out.println(ciphertext);
        Map<String, Object> result = new HashMap<>();
//        JSONObject jsonObject = JSON.parseObject(ciphertext);
//        String text = jsonObject.getString("ciphertext");
//        String key = "X2!k4@L7#q9M6p8R";//测试环境
        String key = "F9#q7A@3r5G6p2WR";//生产环境
        Sm4Cipher sm4Cipher = new Sm4Cipher();

        Map<String,Object> reqmap = ((Map<String,Object>) JSON.parse(sm4Cipher.decrypt(ciphertext, key)));


        String bimRequestId = (String) reqmap.get("bimRequestId");
        String bimUid = (String) reqmap.get("bimUid");
//        String bimUid = "lA28EIVL9sdsAHVc";
        Boolean ENABLE = (Boolean) reqmap.get("__ENABLE__");
//        System.out.println(ENABLE);
        String ids = userCreateService.getId(bimUid);

        if (Objects.equals(ids, "")){
            result.put("bimRequestId",bimRequestId);
            result.put("resultCode", 500);
            result.put("message", "未找到账号");
            System.out.println("未找到账号");
//            return result;
            String target2 = sm4Cipher.encrypt(JSON.toJSONString(result), key);
            return target2;
        }

        String bimRemoteUser = (String) reqmap.get("bimRemoteUser");
//        String bimRemotePwd = (String) reqmap.get("bimRemotePwd");
        String username = (String) reqmap.get("username");
//        String username = "test";
//        String password = (String) reqmap.get("password");
//        String password = "123456";

        if (BamboocloudUtils.verify(reqmap,"SM3").booleanValue()) {
            System.out.println("验签成功");
            try {
//            registerVo.get__ENABLE__;
                RegisterVo registerVo = new RegisterVo();
                if (ENABLE == null) {
//                    registerVo.setIsDisabled(4);
                }
                else if (ENABLE) {
                    registerVo.setStatus(0);
                }else if (!ENABLE) {
                    registerVo.setStatus(1);
                }
//                registerVo.setIsDisabled(0);
//                String id =  userCreateService.getId(bimUid);
//                registerVo.setId(id);

                registerVo.setUserName(username);
//                if (password == null) {
//
//                }else if (!password.isEmpty()){
//                    registerVo.setPassword(password);
//                    registerVo.setPassword(MD5.encrypt(registerVo.getPassword()));
//                }
//                registerVo.setBimRemotePwd(bimRemotePwd);
                registerVo.setBimRemoteUser(bimRemoteUser);
//                registerVo.setId(ids);

                userCreateService.updateById(registerVo);
                System.out.println("更新成功");
                result.put("bimRequestId",bimRequestId);
                result.put("resultCode", 0);
                result.put("message", "success");
//                return result;
                String target2 = sm4Cipher.encrypt(JSON.toJSONString(result), key);
                return target2;
            } catch (Exception e) {
                System.out.println("更新失败");
                result.put("bimRequestId", bimRequestId);
                result.put("resultCode", 500);
                result.put("message", "账号更新失败,请联系管理员");
//                return result;
                String target2 = sm4Cipher.encrypt(JSON.toJSONString(result), key);
                return target2;
            }
        }
        System.out.println("验签失败");
        result.put("bimRequestId", bimRequestId);
        result.put("resultCode", 500);
        result.put("message", "验签失败");
//        return result;
        String target2 = sm4Cipher.encrypt(JSON.toJSONString(result), key);
        return target2;
    }

    private Map<String, Object> createAccountAttribute(String name, String type, boolean required, boolean multivalued) {
        Map<String, Object> attribute = new HashMap<>();
        attribute.put("name", name);
        attribute.put("type", type);
        attribute.put("required", required);
        attribute.put("multivalued", multivalued);

        return attribute;
    }

    private static String getParamStr(Map<String, Object> reqmap){
        Map<String, Object> verifymap = new TreeMap<String, Object>();
        StringBuffer sb = new StringBuffer();
        Iterator<String> it = reqmap.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            verifymap.put(key, reqmap.get(key));
        }
        Iterator<String> ittree = verifymap.keySet().iterator();
        while (ittree.hasNext()) {
            String key = (String) ittree.next();
            if (!"signature".equals(key)) {
                sb.append(key).append("=").append(verifymap.get(key)).append("&");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    @PostMapping("/TEST")
    public String TEST(ServerWebExchange exchange, @RequestBody String registerVo) {
//        String key = "X2!k4@L7#q9M6p8R";//测试环境
        String key = "F9#q7A@3r5G6p2WR";//生产环境
        Sm4Cipher sm4Cipher = new Sm4Cipher();

        Map<String,Object> reqmap = ((Map<String,Object>) JSON.parse(sm4Cipher.decrypt("JZ67jlJoVYxy9o/fMRERagrBWqv61lKMcWQJiKFoyAtEB43ZmuoqpVjzY1o0OiMIs1u6xOtyhT/9w+aFU2j1EjCTNAOwxcEpHxMYXu6nnLKfIBiF+lE2sVorxpVOJygAwnHCq1AV6f9Tn8AYrKWB4Cp8eGIRAWPlADRV3HwSrZNyjxhCPF/5BVaRvk7YAsra2IRL/VRo4EqFfc9sHEJGZJgqJfPv1stctZaOf+ZKppsPsywfCuFywvpq7352V7Ls1CjmRazvMvvrej+YC5Ry+g==", key)));

        String bimRemoteUser = (String) reqmap.get("bimRemoteUser");
        String bimRemotePwd = (String) reqmap.get("bimRemotePwd");
        //判断用户名和密码
        System.out.println("bimRemoteUser:"+bimRemoteUser);
        System.out.println("bimRemotePwd:"+bimRemotePwd);

        Boolean result = BamboocloudUtils.verify(reqmap,"SM3");

        if (BamboocloudUtils.verify(reqmap,"SM3").booleanValue()){
            System.out.println("success");
        }
//
//        ServerHttpRequest serverHttpRequest = exchange.getRequest();
////        String bodyparam = BamboocloudUtils.getRequestBody(serverHttpRequest);
//        HttpHeaders headers = serverHttpRequest.getHeaders();
//        MediaType contentType = headers.getContentType();
//
//
//        String key = "X2!k4@L7#q9M6p8R";
//        Sm4Cipher sm4Cipher = new Sm4Cipher();
//
//        Map<String,Object> reqmap = ((Map<String,Object>) JSON.parse(sm4Cipher.decrypt(registerVo, key)));
//
//        String bimRemoteUser = (String) reqmap.get("bimRemoteUser");
//        String bimRemotePwd = (String) reqmap.get("bimRemotePwd");
//        //判断用户名和密码
//        System.out.println("bimRemoteUser:"+bimRemoteUser);
//        System.out.println("bimRemotePwd:"+bimRemotePwd);
//
//        Boolean result = BamboocloudUtils.verify(reqmap,"SM3");
//
//        if (verify(reqmap,"SM3").booleanValue()){
////            String username = (String) reqmap.get("bimRemoteUser");
////            String password = (String) reqmap.get("bimRemotePwd");
////            System.out.println(username);
////            System.out.println(password);
//            System.out.println("success");
//        }
//
        return sm4Cipher.decrypt(registerVo, key);
    }

    @PostMapping("/TEST3")
    public String TEST3(@RequestBody String registerVo) {
//        String key = "X2!k4@L7#q9M6p8R";//测试环境
        String key = "F9#q7A@3r5G6p2WR";//生产环境
        Sm4Cipher sm4Cipher = new Sm4Cipher();
        String result = sm4Cipher.decrypt("nJ/refvXOfE/tEhRB/AiFZzj6SiNy9d7vaOJVleeoDS8zMXta1QdF+DJ9qGLW0TeIL3+6DepwWSmfPK26jCbZ+JUQ1KWRJqR5X53a0vQP4v3hbHVeHqoIXTFitRxOaeG5NXPDHqFb2abS3uHdAgM+ZBikL8HdWLbjyXrMOz/feXEYnKYQ+zP4F6J5JAdd0fc6L2IGgpwxyeAuYiisHTyPw==",key);
        System.out.println(result);
        //        Map<String,Object> reqmap = ((Map<String,Object>) JSON.parse(sm4Cipher.decrypt("JZ67jlJoVYxy9o/fMRERagrBWqv61lKMcWQJiKFoyAtEB43ZmuoqpVjzY1o0OiMIs1u6xOtyhT/9w+aFU2j1EjCTNAOwxcEpHxMYXu6nnLKfIBiF+lE2sVorxpVOJygAwnHCq1AV6f9Tn8AYrKWB4Cp8eGIRAWPlADRV3HwSrZNyjxhCPF/5BVaRvk7YAsra2IRL/VRo4EqFfc9sHEJGZJgqJfPv1stctZaOf+ZKppsPsywfCuFywvpq7352V7Ls1CjmRazvMvvrej+YC5Ry+g==", key)));
//
//        String bimRemoteUser = (String) reqmap.get("bimRemoteUser");
//        String bimRemotePwd = (String) reqmap.get("bimRemotePwd");
//        //判断用户名和密码
//        System.out.println("bimRemoteUser:"+bimRemoteUser);
//        System.out.println("bimRemotePwd:"+bimRemotePwd);
//
//        Boolean result = verify(reqmap,"SM3");
//
//        if (verify(reqmap,"SM3").booleanValue()){
//            System.out.println("success");
//        }
        return result;
    }

    public static void main(String[] args) {
        String key = "X2!k4@L7#q9M6p8R";//测试环境
//        String key = "F9#q7A@3r5G6p2WR";//生产环境
        Sm4Cipher sm4Cipher = new Sm4Cipher();
//        String ciphertext = "nJ/refvXOfE/tEhRB/AiFZzj6SiNy9d7vaOJVleeoDS8zMXta1QdF+DJ9qGLW0TeIL3+6DepwWSmfPK26jCbZ+JUQ1KWRJqR5X53a0vQP4v3hbHVeHqoIXTFitRxOaeG5NXPDHqFb2abS3uHdAgM+ZBikL8HdWLbjyXrMOz/feXEYnKYQ+zP4F6J5JAdd0fc6L2IGgpwxyeAuYiisHTyPw==";
        String ciphertext = "8mFYSBDz4CSa9cDgQxfsivwyQdnuPs3os2k0Ux3DtlD8jh+4JNmLaYZYRaGSlMfLKE8Xd957N5cc8EMLptJYjEoSAos81lbzO8chssHRNOVVeraQ11VOmhmVo9ru3SLZBR+3ouUoEgBEHy3v9tGzWeKx5qahpPhfZ+giYFPHz112/hvetPyd85016XyyzRXy\n";
        String result2 = sm4Cipher.decrypt(ciphertext, key);

//        System.out.println(result);

        System.out.println(result2);
    }

//    public static void main(String[] args) {
//        String key = "X2!k4@L7#q9M6p8R";//测试环境
////        String key = "F9#q7A@3r5G6p2WR";//生产环境
//        Sm4Cipher sm4Cipher = new Sm4Cipher();
//        Map<String, Object> result = new HashMap<>();
//        result.put("bimRequestId", "测试");
//        result.put("resultCode", "0");
//        result.put("message", "success");
//        String sign = sign(result);
//        System.out.println("sing:"+sign);
//        String target2 = sm4Cipher.encrypt(sign, key);
//        System.out.println(target2);
//    }

    static String sign(Map<String, Object> param) {
        StringBuffer sb = new StringBuffer();
        Iterator<String> it = param.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            sb.append(key).append("=").append(param.get(key)).append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        Sm3Signature signature = new Sm3Signature();
        System.out.println(sb.toString());
        String sign = signature.signature(sb.toString());
        param.put("signature", sign);
        return JSONObject.toJSONString(param);
    }

    @GetMapping("/TEST2")
    public String TEST2() {
        return "success";
    }
}
